public class DiscussionImagesController {
	
	public String idDiscussion = null;
	public UserPermissions userPermissions=new UserPermissions();
	public String delConfirm = '';
	public String imgInUse = '';
	
	// max attachment size bytes
    public final Integer MAX_SIZE = 5240000;
    
    public Boolean validAttSize = true;
    
    public DiscussionImagesController(){
    	if(idDiscussion == null)
    		idDiscussion = System.currentPageReference().getParameters().get('id');
    	genPermissions();
    	
    }
    
    public void deleteImage(){
    	Attachment att = new Attachment();
    	String imageId = System.currentPageReference().getParameters().get( 'imageId' );
    	
    	System.debug( '|||||' + imageId);
    	att = [ SELECT Id FROM Attachment WHERE Id =: imageId ];
    	if( att != null ){
    		
    		List<DiscussionMessage__c> atts =  new List<DiscussionMessage__c>();
    		atts = (List<DiscussionMessage__c>)[FIND :( '*' + imageId + '*') IN ALL FIELDS RETURNING DiscussionMessage__c (Message__c)][0];
    		if( atts.size() > 0 )
    			this.imgInUse = 'Image in Use, in ' + atts.size() + ' messages.';
				    		
    		delConfirm = imageId;
    		String confirm = System.currentPageReference().getParameters().get( 'confirm' );
    		if( confirm == 'Yes')
	    	delete att;
    	}
    }
    public String getDelConfirm(){
    	return delConfirm;
    }
    
    public void restoreDeleteEvent(){
    	delConfirm = '';	
    }
	
	public String getimgInUse(){
		return imgInUse;
	}
    public void genPermissions() {
		userPermissions.setId(UserInfo.getUserId());
		userPermissions.setTeam(idDiscussion);
		userPermissions.setObjectType('DiscussionForum');
		userPermissions.setPermissions();		
	}
    
	/**
	* Set parent id for Attachment instance
	*@param String
	*/
	public void setIdDiscussion (String idWiki) {
		this.idDiscussion = idWiki;
	}
	
	/**
	*@return String
	*/
	public String getDiscussion () {
		return this.idDiscussion;
	}
    
	/**
	*@return Boolean
	*/
	public Boolean getValidAttSize(){
		return validAttSize;
	}	
	
	// New Attachment Object
	public Attachment newAttach = new Attachment();
	
	/**
	*@param Attachment
	*/
	public void setNewAttach (Attachment newAttach) {
		this.newAttach = newAttach;	
	}
	
	/**
	*@return Attachment
	*/
	public Attachment getNewAttach () {
		return newAttach;
	}
	
	/**
	* Save new image
	*@return PageReference
	*/
	public PageReference saveNewImage () {
		
		System.debug( '###: ' + this.idDiscussion );
		newAttach.ParentId = this.idDiscussion;
		PageReference pageRef = ApexPages.currentPage();
		if(newAttach.BodyLength <= MAX_SIZE || (newAttach.name != null || newAttach.name != '') || (this.idDiscussion != null || this.idDiscussion != '')){
			this.validAttSize = true;
			insert newAttach;
			pageRef.setRedirect(true);
			newAttach = new Attachment();
			return pageRef;
		}else{
			this.validAttSize = false;
			pageRef.setRedirect(true);
			newAttach = new Attachment();
			return pageRef;
		}
	}
	
    /**
    *@return List<AttachmentInfo>
    */
    public List<AttachmentInfo> getAttachments() {
    	List<Attachment> Attachments = new List<Attachment>();
    	if (idDiscussion == '{!idDiscussion}') {
    		Attachments = [select name, id, parentid, ContentType,CreatedById from attachment order by name];
    	}else {
    		Attachments = [select name, id, parentid, ContentType,CreatedById from attachment where parentid=:idDiscussion order by name];
    	}
    	List<AttachmentInfo> infos = new List<AttachmentInfo>();
    	
    	DiscussionForum__c actForum = new DiscussionForum__c();
    	actForum = [ SELECT PictureId__c FROM DiscussionForum__c WHERE Id =: idDiscussion LIMIT 1 ];
		
		Integer position = 1;

		for (Attachment item: Attachments){	
            AttachmentInfo info = new AttachmentInfo();
            info.setId(item.Id);
            info.setName(item.Name);
            info.setIsAvatar( ( item.id == actForum.PictureId__c) ? true : false );

            info.setPos( position );
            position++;
            
            String ContentType = item.ContentType;
            String image = '';
       		
       		if (ContentType == null || ContentType == '') {
            	// Using extension
            	Integer extPos = item.Name.lastIndexOf('.') + 1;
            	String extension = item.Name.substring(extPos);
            	// containsKey does a case sensitive comparison
            	extension = extension.toLowerCase();
            	Map<String, String> typesExt = new Map<String, String>{
           			'png' => 'images.gif',
           			'jpg' => 'images.gif',
           			'gif' => 'images.gif'
       			};
           		if(typesExt.containsKey(extension)) {
           			image = typesExt.get(extension);
           		}
            }else {
           		// Using mime type
           		Map<String, String> typesMime = new Map<String, String>{
           			'image/jpeg' => 'images.gif', 
           			'image/pjpeg' => 'images.gif', 
           			'image/png' => 'images.gif', 
           			'image/x-png' => 'images.gif', 
           			'image/gif' => 'images.gif', 
           			'image/bmp' => 'images.gif'
       			};	
           		if(typesMime.containsKey(ContentType)) {
           			image = typesMime.get(ContentType);
           		}
            }
       		
       		// MIME TYPE
       		if (UserInfo.getUserId()== item.CreatedById || userPermissions.getCanManage()){
       			info.setAttachImage(image);
            	infos.add(info);
       		}
            
        }	
        return infos;   	    									
    }     
    
    /**
    *@return Integer
    */
    public Integer getAttachCount () {
    	return [select count() from attachment where parentid=:idDiscussion];
    }
    
	/**
	* Class AttachmentInfo
	*/ 	 
	public class AttachmentInfo {
        
        String name;
        String attachImage;
		String id;
		Boolean isAvatar = false;
        Integer position;
        /**
        *@return String
        */
        public String getId () {
        	return id;
        }
        
        /**
        *@param String
        */
        public void setId (String id) {
        	this.id = id;
        }
        
        /**
        *@return String
        */
        public String getName() {
                return name;
        }

        /**
        *@param String
        */
        public void setName(String name) {
                this.name = name;
        }  
        
        /**
        *@return String
        */
        public String getAttachImage() {
                return attachImage;
        }

        /**
        *@param String
        */
        public void setAttachImage (String attachImage) {
                this.attachImage = attachImage;
        }          
        
        /**
        *@return Boolean
        */
        public Boolean getIsAvatar(){
        	return isAvatar;
        }

        /**
        *@param Boolean
        */
        public void setIsAvatar( Boolean b){
        	isAvatar = b;
        }
                                        
        /**
        *@return Integer
        */
        public Integer getPos(){
        	return position;
        }

        /**
        *@param Integer
        */
        public void setPos( Integer b){
        	position = b;
        }
	}
}